package com.nengchuan.kbms.dfs.service;

import com.nengchuan.config.exception.NcException;
import com.nengchuan.kbms.common.AutoWrapper;
import com.nengchuan.kbms.common.PageServiceImpl;
import com.nengchuan.kbms.dfs.dao.ManufacturerMapper;
import com.nengchuan.kbms.dfs.entity.dto.ManufacturerDTO;
import com.nengchuan.kbms.dfs.entity.po.Manufacturer;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 供应商 服务实现类
 * </p>
 *
 * @author abe
 * @since 2020-04-24
 */
@Service
public class ManufacturerServiceImpl extends PageServiceImpl<ManufacturerMapper, Manufacturer> implements ManufacturerService {

    /**
     * 新增供应商
     * 1. 检查供应商名称是否已存在，如果存在不允许新增
     */
    @Override
    public Long insert(ManufacturerDTO dto) {
        String name = dto.getManufacturerName().trim();
        Manufacturer manufacturer = getOne(new AutoWrapper<>(dto), false);
        if (manufacturer != null) {
            throw new NcException("新增失败，供应商已存在");
        }
        return super.insert(dto).getId();
    }

    /**
     * 修改供应商
     * 1. 检查dto
     */
    @Override
    public boolean update(ManufacturerDTO dto) {
        if (dto.getId() == null) {
            throw new NcException("供应商id不能为空");
        }
        String name = dto.getManufacturerName().trim();
        Manufacturer own = getById(dto.getId());
        if (!name.equals(own.getManufacturerName())) {
            Manufacturer manufacturer = getOne(new AutoWrapper<>(dto), false);
            if (manufacturer != null) {
                throw new NcException("修改失败，供应商已存在");
            }
            return super.update(dto);
        }
        // 无需修改，供应商名称未变动
        return false;
    }

}
